package com.lanou.bookstore.user.dao;

import com.lanou.bookstore.user.domain.User;
import com.lanou.bookstore.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

public class RegisterDao {
    public boolean register(User user) {
        Connection conn = JDBCUtil.getConn();
        try {
            // 插入注册信息

            String uid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            String sqlInsert = "INSERT INTO tb_user (uid, username, password) " +
                    "VALUES ( ?, ?, ?)";
            PreparedStatement psInsert = conn.prepareStatement(sqlInsert);
            psInsert.setString(1, uid);
            psInsert.setString(2, user.getUsername());
            psInsert.setString(3, user.getPassword());
            psInsert.executeUpdate();
            psInsert.close();
            return true;// 注册成功
        } catch (Exception e) {
            try {
                // 在catch中回滚
                // 如果哪条sql,抛异常了,我们可以回滚到sql执行之前
                conn.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return false;
    }

    public boolean hasThisName(String username) {

        String sql = "SELECT COUNT(*) FROM tb_user WHERE username = ?";
        Connection conn = JDBCUtil.getConn();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet resultSet = ps.executeQuery();
            resultSet.next();
            int count = resultSet.getInt(1);

            resultSet.close();
            ps.close();
            return count > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
